package com.yin.myproject.spring.context.support;

import com.yin.myproject.spring.beans.BeansException;
import com.yin.myproject.spring.context.ConfigurableApplicationContext;
import com.yin.myproject.spring.core.env.ConfigurableEnvironment;
import com.yin.myproject.spring.core.env.StandardEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Eason
 * @create 2018-01-06 21:17
 **/
public class AbstractApplicationContext implements ConfigurableApplicationContext {

    private static final Logger logger = LoggerFactory.getLogger(AbstractApplicationContext.class);

    private final Object startupShutdownMonitor = new Object();
    private long startupDate;
    private final AtomicBoolean active = new AtomicBoolean();
    private final AtomicBoolean closed = new AtomicBoolean();
    private ConfigurableEnvironment environment;

    public ConfigurableEnvironment getEnvironment() {
        if(this.environment == null){
            this.environment = createEnvironment();
        }
        return environment;
    }

    private ConfigurableEnvironment createEnvironment() {
        return new StandardEnvironment();
    }

    public void setEnvironment(ConfigurableEnvironment environment) {
        this.environment = environment;
    }

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            prepareRefresh();
        }
    }

    private void prepareRefresh() {
        this.startupDate = System.currentTimeMillis();
        this.closed.set(false);
        this.active.set(true);

        logger.info("Refreshing " + this);

        initPropertySources();

        getEnvironment().validateRequiredProperties();
    }


    private void initPropertySources() {
    }

    public static void main(String[] args) {
        Properties properties = System.getProperties();
        System.out.println(properties);
    }
}
